<?php
namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Jobs\AddRegisterHongBaoJob;
use App\Jobs\AddIMFriends;
use App\Jobs\GetMobileCityIdJob;
use App\Jobs\MLMJob;
use App\Jobs\PushMsgJob;
use App\Jobs\RegisterJob;
use App\Jobs\SendReceiveHongBaoMsgJob;
use App\Jobs\SendSystemMsgJob;
use App\Jobs\SendWelcomeMsgJob;
use App\Jobs\TestJob;
use App\Jobs\VerifyCouponJob;
use App\Libraries\Decorator\Image\CoverDecorator;
use App\Libraries\Easemob\Easemob;
use App\Libraries\Tools\Msg;
use App\Libraries\Tools\URL;
use App\Models\IM\Group;
use App\Models\Msg\MsgSystem;
use App\Models\Post\Post;
use App\Models\Product\Product;
use App\Models\HZLM\HZLM;
use App\Models\Shop\Shop;
use App\Models\Shop\ShopContent;
use App\Models\Shop\ShopCouponPurchase;
use App\Models\Shop\ShopManager;
use App\Models\Shop\ShopService;
use App\Models\Shop\ShopDianping;
use App\Models\Shop\ShopStatistic;
use App\Models\Tmp\TmpManagerJWQNW;
use App\Models\Tmp\TmpShopJWQNW;
use App\Models\Tool\BadWord;
use App\Models\Tool\District;
use App\Models\Tool\Proxy;
use App\Models\Invite\InviteCode;
use App\Models\User\User;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use JMessage\IM\Admin;
use JMessage\IM\Friend;
use JMessage\JMessage;
use OSS\OssClient;
use OSS\Core\OssException;
use Illuminate\Support\Facades\DB;


class APIController extends Controller{

    protected $img_url = 'http://img1.1990design.com/';
    protected $local;

    public function __construct(){}

    public function api(Shop $shop,
                        ShopContent $content,
                        ShopStatistic $sta,
                        ShopService $service,
                        ShopManager $manager,
                        User $user){
        $http = new Client();
        $images = [];
        $this->local = dirname(dirname(dirname(dirname(__DIR__)))).'/public/upload/image/';
        $ossClient = new OssClient(env('ALIYUN_ID'), env('ALIYUN_KEY'), env('ALIYUN_ENDPOINT'));
        $bucket = env('ALIYUN_BUCKET');
        $start = 29;
        $end = 11765;
        for($i=$start; $i<=$end; $i++){
            $data = $http->get('http://mobile.yiluxiangxi.cn/api/shop_detail?id='.$i);
            $data = json_decode($data->getBody(), true);
            if($data['state'] == 1 && !empty($data['data'])){
                $shop->title = isset($data['data']['name'])?$data['data']['name']:'';
                $shop->type = isset($data['data']['shoptype'])?$data['data']['shoptype']:1;
                $shop->consumption = isset($data['data']['peoplefold'])?$data['data']['peoplefold']:300;
                if(isset($data['data']['logo']) && !empty($data['data']['logo']) && $this->check_url($this->img_url.$data['data']['logo'])){
                    $shop->cover = 'image/'.$data['data']['logo'];
//                    try{
//                        $img = file_get_contents($this->img_url.$data['data']['logo']);
//                        file_put_contents($this->local.$data['data']['logo'], $img);
//                        $object = $shop->cover;
//                        $ossClient->uploadFile($bucket, $object, $this->local.$data['data']['logo']);
//                    }catch (\Exception $e){
//                        Log::debug('------>Fail in cover id='.$i);
//                        return $this->sendFailResponse(400,40003);
//                    }
                }
                if(isset($data['data']['moreimg']) && !empty($data['data']['moreimg']) && is_array($data['data']['moreimg'])){
                    $images = [];
                    foreach($data['data']['moreimg'] as $v){
                        if(isset($v['img']) && !empty($v['img']) && $this->check_url($this->img_url.$v['img'])){
                            $images[] = 'image/'.$v['img'];
//                            try{
//                                $img = file_get_contents($this->img_url.$v['img']);
//                                file_put_contents($this->local.$v['img'], $img);
//                                $object = 'image/'.$v['img'];
//                                $ossClient->uploadFile($bucket, $object, $this->local.$v['img']);
//                            }catch (\Exception $e){
//                                Log::debug('------>Fail in images id='.$i);
//                                return $this->sendFailResponse(400,40003);
//                            }
                        }
                    }
                }
                if(!empty($images)){
                    $shop->images = json_encode($images);
                }
                $shop->phone = isset($data['data']['tel'])?$data['data']['tel']:'';
                $shop->address = isset($data['data']['address'])?$data['data']['address']:'';
                $shop->longitude = isset($data['data']['longitude'])?$data['data']['longitude']:0;
                $shop->latitude = isset($data['data']['latitude'])?$data['data']['latitude']:0;
                $shop->save();
                $content->shop_id = $shop->shop_id;
                $content->content = isset($data['data']['desc'])?$data['data']['desc']:'';
                $content->save();
                $content = new ShopContent();
                $sta->shop_id = $shop->shop_id;
                $sta->save();
                $sta = new ShopStatistic();
                if(isset($data['data']['servicelist']) && !empty($data['data']['servicelist']) && is_array($data['data']['servicelist'])){
                    foreach($data['data']['servicelist'] as $v){
                        $service->shop_id = $shop->shop_id;
                        $service->name = isset($v['name'])?$v['name']:'未知';
                        $service->price = isset($v['price'])?$v['price']:'300';
                        $service->save();
                        $service = new ShopService();
                    }
                }
                if(isset($data['data']['manager']) && !empty($data['data']['manager']) && is_array($data['data']['manager'])){
                    foreach($data['data']['manager'] as $v){
                        if(isset($v['phone']) && !empty($v['phone'])){
                            $cur_user = $user->where('mobile', $v['phone'])->first();
                            if(!empty($cur_user)){
                                continue;
                            }
                            $user->mobile = $v['phone'];
                            if(isset($v['img']) && !empty($v['img']) && $this->check_url($this->img_url.$v['img'])){
                                $user->cover = 'image/'.$v['img'];
//                                try{
//                                    $img = file_get_contents($this->img_url.$v['img']);
//                                    file_put_contents($this->local.$v['img'], $img);
//                                    $object = 'image/'.$v['img'];
//                                    $ossClient->uploadFile($bucket, $object, $this->local.$v['img']);
//                                }catch (\Exception $e){
//                                    Log::debug('------>Fail in manager id='.$i);
//                                    return $this->sendFailResponse(400,40003);
//                                }
                            }
                            $user->sign = isset($v['sign'])?$v['sign']:'';
                            $user->save();
                            Easemob::singleton()->createUser($user->user_id, md5($user->user_id));
                            $manager->user_id = $user->user_id;
                            $manager->shop_id = $shop->shop_id;
                            if(isset($v['name']) && !empty($v['name'])){
                                $manager->name = $v['name'];
                            }
                            $manager->company = $shop->title;
                            $manager->save();
                            $user = new User();
                            $manager = new ShopManager();
                        }
                    }
                }
                $shop = new Shop();
            }
            Log::debug('------>success id='.$i);
        }
        return $this->sendSuccessResponse(['start_id'=>$start,'end_id'=>$end]);
    }

    public function spiderForJWQNW(TmpShopJWQNW $tmpShopJWQNW, TmpManagerJWQNW $tmpManagerJWQNW){
        $http = new Client();
        $start = 29;
        $end = 11765;
        for($i=$start; $i<=$end; $i++){
            $data = $http->get('http://mobile.yiluxiangxi.cn/api/shop_detail?id='.$i);
            $data = json_decode($data->getBody(), true);
            if($data['state'] == 1 && !empty($data['data'])){
//                $tmpShopJWQNW->title = isset($data['data']['name'])?$data['data']['name']:'';
//                $tmpShopJWQNW->type = isset($data['data']['shoptype'])?$data['data']['shoptype']:1;
//                $tmpShopJWQNW->tel = isset($data['data']['tel'])?$data['data']['tel']:'';
//                $tmpShopJWQNW->address = isset($data['data']['address'])?$data['data']['address']:'';
//                $tmpShopJWQNW->longitude = isset($data['data']['longitude'])?$data['data']['longitude']:0;
//                $tmpShopJWQNW->latitude = isset($data['data']['latitude'])?$data['data']['latitude']:0;
//                $tmpShopJWQNW->save();
//                $tmpShopJWQNW = new TmpShopJWQNW();
                $shop = $tmpShopJWQNW->where('title', $data['data']['name'])
                    ->where('type', $data['data']['shoptype'])
                    ->where('tel', $data['data']['tel'])
                    ->where('address', $data['data']['address'])
                    ->where('longitude', $data['data']['longitude'])
                    ->where('latitude', $data['data']['latitude'])->first();
                if(isset($data['data']['manager']) && !empty($data['data']['manager']) && is_array($data['data']['manager'])) {
                    foreach($data['data']['manager'] as $v){
                        $tmpManagerJWQNW->shop_id = $shop->id??0;
                        $tmpManagerJWQNW->manager = $v['name']??'';
                        $tmpManagerJWQNW->phone = $v['phone']??'';
                        $tmpManagerJWQNW->save();
                        $tmpManagerJWQNW = new TmpManagerJWQNW();
                    }

                }
            }
            Log::debug('success in '. $i);
        }
    }

    public function getDianPingShopIds(){
        $city_list = array(
            '北京'=>2,
            '上海'=>1,
            '广州'=>4,
            '深圳'=>7,
            '成都'=>8,
            '武汉'=>16,
            '重庆'=>9,
            '南京'=>5,
            '天津'=>10,
            '杭州'=>3,
            '苏州'=>6,
            '西安'=>17,
            '长沙'=>344,
            '沈阳'=>18,
            '青岛'=>21,
            '郑州'=>160,
            '大连'=>19,
            '东莞'=>219,
            '宁波'=>11,
            '无锡'=>13,
            '佛山'=>208,
            '福州'=>14,
            '北海'=>228
        );

        $category_list = array(
            'KTV'=>'g135',
            '量贩式KTV'=>'g2890',
            '会所型KTV'=>'g2892',
            '足疗按摩'=>'g141',
            '洗浴/汗蒸'=>'g140',
            '酒吧'=>'g133',
            '清吧'=>'g33950',
            '夜店'=>'g2951',
            'Live House'=>'g33951',
            '闹吧'=>'g33949',
            '其他酒吧'=>'g33952'
        );

        $sort_list = array(
            '默认'=>'',
            '智能'=>'n10',
            '好评'=>'o3',
            '人气'=>'o2',
            '总分'=>'o5',
            '点评最多'=>'o10',
            '人均最高'=>'o8',
            '人均最低'=>'o8b1'
        );

        if(!empty($_GET['city'])){
            if(array_key_exists($_GET['city'],$city_list)||in_array($_GET['city'],$city_list)){
                $city_id = is_numeric($_GET['city'])?$_GET['city']:$city_list["{$_GET['city']}"];
            }else{
                return $this->sendFailResponse('400','10002');
            }
        }else{
            return $this->sendFailResponse('400','10001');
        }
        if(!empty($_GET['category'])) {
            if(array_key_exists($_GET['category'],$category_list)||in_array($_GET['category'],$category_list)) {
                $category = preg_match('/\w+\d+/', $_GET['category']) ? $_GET['category']:$category_list["{$_GET['category']}"];
            }else{
                return $this->sendFailResponse('400','10002');
            }
        }else{
            return $this->sendFailResponse('400','10001');
        }
        if(!empty($_GET['sort'])) {
            $sort = preg_match('/\W+/',$_GET['sort'])?$sort_list["{$_GET['sort']}"]:$_GET['sort'];
        }else{
            $sort = $sort_list['默认'];
        }
        if(!empty($_GET['limit'])) {
            $limit = abs(intval($_GET['limit']));
        }else{
            $limit = 1500;
        }
        if(!empty($_GET['rep_shop_ids'])&&$_GET['rep_shop_ids']==1){
            $rep_shop_ids = ShopDianping::pluck('dp_shop_id')->toArray();
        }else{
            $rep_shop_ids = [];
        }
        $limit_page = ceil($limit/15);
        for($page=1,$shop_ids=[];$page<=$limit_page;$page++){
            $url='http://www.dianping.com/search/category/'.$city_id.'/30/'.$category.$sort.'p'.$page;
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);
            curl_setopt($ch, CURLOPT_MAXREDIRS,2);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $file_contents = curl_exec($ch);
            curl_close($ch);
            preg_match('/shopIDs:\s*\[([\s\d,]*),\s*\]/', $file_contents, $match);
            if(!empty($match)){
                $str_shop_ids = preg_replace('/\s/','',$match[1]);
                $page_shop_ids = explode(',',$str_shop_ids);
            }else{
                $page_shop_ids = [];
            }
            if(!empty($page_shop_ids)){
                $shop_ids = array_unique(array_merge($shop_ids,$page_shop_ids));
                if($page == $limit_page||$page==50){
                    if(!empty($rep_shop_ids)){
                        $intersection = array_intersect($shop_ids,$rep_shop_ids);
                        $shop_ids = array_diff($shop_ids,$intersection);
                    }
                    if($page==50){
                        break;
                    }
                    $results_total = count($shop_ids);
                    $differ = $limit-$results_total;
                    if($differ>0){
                        $differ_page = ceil($differ/15);
                        $limit_page = $limit_page+$differ_page;
                    }
                }
            }else{
                if(!empty($rep_shop_ids)){
                    $intersection = array_intersect($shop_ids,$rep_shop_ids);
                    $shop_ids = array_diff($shop_ids,$intersection);
                }
                break;
            }
        }
        $shop_ids = array_slice(array_unique($shop_ids),0,$limit);
        Log::debug('------>getDianPingShopIds='.json_encode($shop_ids));
        return $this->sendSuccessResponse($shop_ids);
    }

    public function getDianPingShopInfo(){
        if(!empty($_GET['shop_ids'])){
            $shop_ids = json_decode($_GET['shop_ids'],true);
            if(empty($shop_ids)||!is_numeric($shop_ids[0])){
                return $this->sendFailResponse('400','10002');
            }
        }else{
            return $this->sendFailResponse('400','10001');
        }
        if(isset($_GET['shop_photo_limit'])){
            $shop_photo_limit = abs(intval($_GET['shop_photo_limit']));
        }else{
            $shop_photo_limit = 0;
        }
        if(!empty($_GET['proxy'])&&!empty($_GET['proxy_port'])){
            $proxy = $_GET['proxy'];
            $proxy_port = abs(intval($_GET['proxy_port']));
            if(!empty($_GET['proxy_user'])&&!empty($_GET['proxy_pwd'])){
                $proxy_user = $_GET['proxy_user'];
                $proxy_pwd = $_GET['proxy_pwd'];
            }
        }
        if(isset($_GET['use_random_proxy'])&&in_array($_GET['use_random_proxy'],[0,1,2])){
            $use_random_proxy = $_GET['use_random_proxy'];
        }else{
            $use_random_proxy = 0;
        }
        $shop_info = [];
        $success_shop_id = [];
        foreach ($shop_ids as $shop_id){
            $shop_url = 'http://www.dianping.com/shop/'.$shop_id;
            for($i=5;$i>0;$i--){
                $success_one = false;
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $shop_url);
                if($use_random_proxy==1){
                    $proxy_num = Proxy::where('dp_validity','>',0)->where('dp_fail', 0)->count();
                    if($proxy_num>0){
                        $random_proxy = Proxy::where('dp_validity','>',0)->where('dp_fail', 0)->inRandomOrder()->first();
                        $proxy = $random_proxy->proxy;
                        $proxy_port = $random_proxy->port;
                        $proxy_user = $random_proxy->user;
                        $proxy_pwd = $random_proxy->password;
                    }else{
                        Log::debug('--------->No usable proxy!');
                        break 2;
                    }
                }
                if($use_random_proxy==2){//阿布云HTTP代理隧道动态版
                    $proxy = 'http-dyn.abuyun.com';
                    $proxy_port = 9020;
                    $proxy_user = 'H3W545ZSP4VM250D';
                    $proxy_pwd = 'B9EC39E61333D50B';
                }
                if(!empty($proxy)&&!empty($proxy_port)){
                    curl_setopt($ch, CURLOPT_PROXY, $proxy); //代理服务器地址
                    curl_setopt($ch, CURLOPT_PROXYPORT, $proxy_port); //代理服务器端口
                    curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); //使用http代理模式
                    if(!empty($proxy_user)&&!empty($proxy_pwd)){
                        curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC); //代理认证模式
                        curl_setopt($ch, CURLOPT_PROXYUSERPWD, "$proxy_user:$proxy_pwd"); //http代理认证帐号，username:password的格式
                    }
                }
                curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                    'Accept-Encoding:gzip, deflate',
                    'Accept-Language:zh-CN,zh;q=0.8,th;q=0.6',
                    'Cache-Control:max-age=0',
                    'Connection:keep-alive',
                    'Host:www.dianping.com',
                    'Upgrade-Insecure-Requests:1',
                    'Referer:http://www.dianping.com/',
                    'User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36'
                ));
                curl_setopt($ch, CURLOPT_ENCODING, "");
                curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);
                curl_setopt($ch, CURLOPT_MAXREDIRS,2);
                curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
                curl_setopt($ch, CURLOPT_TIMEOUT, 5);
                $file_contents = curl_exec($ch);
                curl_close($ch);
                $forbidden = preg_match('/403 Forbidden/', $file_contents);
                $body_id = preg_match('/body id="top"/', $file_contents);
                if($forbidden){
                    if(isset($random_proxy)){
                        $random_proxy->dp_fail = $random_proxy->dp_fail+1;
                        $random_proxy->dp_validity = 0;
                        $random_proxy->save();
                        $i++;
                    }elseif($use_random_proxy==2){
                        Log::debug('Forbidden Abuyun to getDianPingShopInfo!dp_shop_id='.$shop_id.',file_contents='.$file_contents);
                        $i++;
                    }else{
                        Log::debug('Forbidden to getDianPingShopInfo!dp_shop_id='.$shop_id.',file_contents='.$file_contents);
                        break 2;
                    }
                }elseif($body_id){
                    $shop_closed = preg_match('/shop-closed/', $file_contents);
                    preg_match('/shop_config=[\s\S]*}\s*<\/script>/', $file_contents, $shop_info_match);
                    if(!empty($shop_info_match[0])&&empty($shop_closed)){
                        preg_match('/avgPriceTitle[\s\S]*：(\d+)元/U', $file_contents, $avg_price_match);
                        preg_match('/itemprop="street-address" title="([\s\S]*)">/U', $file_contents, $street_address_match);
                        preg_match('/itemprop="tel">([\s\S]*)<\/span>/U', $file_contents, $phone_match);
                        preg_match('/userId:\s*(\d+),/',$shop_info_match[0],$user_id_match);
                        preg_match('/shopId:\s*(\d+),/',$shop_info_match[0],$shop_id_match);
                        preg_match('/shopCityId:\s*(\d+),/',$shop_info_match[0],$shop_city_id_match);
                        preg_match('/shopName:\s*"([\s\S]*)",\s*address/',$shop_info_match[0],$shop_name_match);
                        preg_match('/address:\s*"([\s\S]*)",\s*publicTransit/',$shop_info_match[0],$address_match);
                        preg_match('/publicTransit:\s*"([\s\S]*)",\s*cityId/',$shop_info_match[0],$public_transit_match);
                        preg_match('/cityId:\s*(\d+),/',$shop_info_match[0],$city_id_match);
                        preg_match('/cityCnName:\s*"([\s\S]*)",\s*cityName/',$shop_info_match[0],$city_cn_name_match);
                        preg_match('/cityName:\s*"([\s\S]*)",\s*cityEnName/',$shop_info_match[0],$city_name_match);
                        preg_match('/cityEnName:\s*"([\s\S]*)",\s*isOverseasCity/',$shop_info_match[0],$city_en_name_match);
                        preg_match('/isOverseasCity:\s*(\d+),/',$shop_info_match[0],$is_over_seas_city_match);
                        preg_match('/fullName:\s*"([\s\S]*)",\s*shopGlat/',$shop_info_match[0],$full_name_match);
                        preg_match('/shopGlat:\s*"(\d+\.\d+)",/',$shop_info_match[0],$shop_glat_match);
                        preg_match('/shopGlng:\s*"(\d+\.\d+)",/',$shop_info_match[0],$shop_glng_match);
                        preg_match('/cityGlat:\s*"(\d+\.\d+)",/',$shop_info_match[0],$city_glat_match);
                        preg_match('/cityGlng:\s*"(\d+\.\d+)",/',$shop_info_match[0],$city_glng_match);
                        preg_match('/power:\s*(\d+),/',$shop_info_match[0],$power_match);
                        preg_match('/shopPower:\s*(\d+),/',$shop_info_match[0],$shop_power_match);
                        preg_match('/voteTotal:\s*(\d+),/',$shop_info_match[0],$vote_total_match);
                        preg_match('/district:\s*(\d+),/',$shop_info_match[0],$district_match);
                        preg_match('/shopType:\s*(\d+),/',$shop_info_match[0],$shop_type_match);
                        preg_match('/mainRegionId:\s*(\d+),/',$shop_info_match[0],$main_region_id_match);
                        preg_match('/mainCategoryName:\s*"([\s\S]*)",\s*categoryURLName/',$shop_info_match[0],$main_category_name_match);
                        preg_match('/categoryURLName:\s*"([\s\S]*)",\s*shopGroupId/',$shop_info_match[0],$category_url_name_match);
                        preg_match('/shopGroupId:\s*(\d+),/',$shop_info_match[0],$shop_group_id_match);
                        preg_match('/categoryName:\s*"([\s\S]*)",\s*loadUserDomain/',$shop_info_match[0],$category_name_match);
                        preg_match('/loadUserDomain:\s*"([\s\S]*)",\s*map/',$shop_info_match[0],$load_user_domain_match);
                        preg_match('/map:\{\s*power:\s*(\d+),\s*manaScore:\s*(\d+)\s*\},\s*mainCategoryId/',$shop_info_match[0],$map_match);
                        preg_match('/mainCategoryId:\s*(\d+),/',$shop_info_match[0],$main_category_id_match);
                        preg_match('/defaultPic:\s*"([\s\S]*)"\s*}\s*<\/script>/',$shop_info_match[0],$default_pic_match);
                        preg_match('/http[\s\S]*(?:\.jpg|\.png|\.jpeg|\.bmp|(?=%))/U',$default_pic_match[1],$cover_match);
                        $shop_photos = [];
                        if(!empty($shop_photo_limit)){
                            $shop_photo_url = 'http://www.dianping.com/shop/'.$shop_id.'/photos/tag-%E7%8E%AF%E5%A2%83';
                            $ch = curl_init();
                            curl_setopt($ch, CURLOPT_URL, $shop_photo_url);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
                            curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);
                            curl_setopt($ch, CURLOPT_MAXREDIRS,2);
                            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                            $file_contents = curl_exec($ch);
                            curl_close($ch);
                            preg_match_all('/btnPraise(\d+)/', $file_contents, $shop_photo_id_match);
                            if(!empty($shop_photo_id_match[1])){
                                $shop_photo_ids = array_slice($shop_photo_id_match[1],0,$shop_photo_limit);
                                foreach($shop_photo_ids as $shop_photo_id){
                                    $photo_url = 'http://www.dianping.com/photos/'.$shop_photo_id.'/type';
                                    $ch = curl_init();
                                    curl_setopt($ch, CURLOPT_URL, $photo_url);
                                    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
                                    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);
                                    curl_setopt($ch, CURLOPT_MAXREDIRS,2);
                                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                                    $file_contents = curl_exec($ch);
                                    curl_close($ch);
                                    preg_match('/J_main-img[\s\S]*(http[\s\S]*(?:\.jpg|\.png|\.jpeg|\.bmp|(?=%)))/U',$file_contents,$photo_match);
                                    if(!empty($photo_match[1])){
                                        $shop_photos[] = $photo_match[1];
                                    }
                                }
                            }
                        }
                        $shop_info[] = [
                            'user_id' => (int)$user_id_match[1],
                            'shop_id' => (int)$shop_id_match[1],
                            'shop_city_id' => (int)$shop_city_id_match[1],
                            'shop_name' => $shop_name_match[1],
                            'avg_price' => empty($avg_price_match[1])?0:(int)$avg_price_match[1],
                            'address' => $address_match[1],
                            'street_address' => $street_address_match[1]??'',
                            'public_transit' => $public_transit_match[1],
                            'phone' => $phone_match[1]??'',
                            'city_id' => (int)$city_id_match[1],
                            'city_cn_name' => $city_cn_name_match[1],
                            'city_name' => $city_name_match[1],
                            'city_en_name' => $city_en_name_match[1],
                            'is_over_seas_city' => (int)$is_over_seas_city_match[1],
                            'full_name' => $full_name_match[1],
                            'shop_glat' => empty($shop_glat_match[1])?0:(float)$shop_glat_match[1],
                            'shop_glng' => empty($shop_glng_match[1])?0:(float)$shop_glng_match[1],
                            'city_glat' => empty($city_glat_match[1])?0:(float)$city_glat_match[1],
                            'city_glng' => empty($city_glng_match[1])?0:(float)$city_glng_match[1],
                            'power' => (int)$power_match[1],
                            'shop_power' => (int)$shop_power_match[1],
                            'vote_total' => (int)$vote_total_match[1],
                            'district' => (int)$district_match[1],
                            'shop_type' => (int)$shop_type_match[1],
                            'main_region_id' => (int)$main_region_id_match[1],
                            'main_category_name' => $main_category_name_match[1],
                            'category_url_name' => $category_url_name_match[1],
                            'shop_group_id' => (int)$shop_group_id_match[1],
                            'category_name' => $category_name_match[1],
                            'load_user_domain' => $load_user_domain_match[1],
                            'map' => [
                                'power' => (int)$map_match[1],
                                'manaScore' => (int)$map_match[2]
                            ],
                            'main_category_id' => (int)$main_category_id_match[1],
                            'default_pic' => $default_pic_match[1],
                            'cover' => $cover_match[0]??$default_pic_match[1],
                            'photos' => $shop_photos
                        ];
                        Log::debug('Success to getDianPingShopInfo!dp_shop_id='.$shop_id_match[1]);
                        $success_shop_id[] = (int)$shop_id_match[1];
                    }else{
                        $shop_info[] = null;
                        Log::debug('Fail to getDianPingShopInfo!dp_shop_id='.$shop_id.(!empty($shop_closed)?',the shop is closed':''));
                    }
                    $success_one = true;
                }else{
                    if($i == 1){
                        $shop_info[] = null;
                        Log::debug('Fail to getDianPingShopInfo body!dp_shop_id='.$shop_id.',file_contents='.$file_contents);
                    }
                    if(isset($random_proxy)) {
                        $random_proxy->dp_fail = $random_proxy->dp_fail + 1;
                        $random_proxy->save();
                    }
                }
                if(isset($random_proxy)){
                    unset($random_proxy);
                }
                if($use_random_proxy!=2){
                    $microsecond = rand(3000000,5000000);
                    usleep($microsecond/(!empty($proxy_num)?$proxy_num:1));
                }
                if(!empty($success_one)){
                    break;
                }
            }
        }
        if(empty($success_shop_id)){
            Log::debug('No success_shop_id to getDianPingShopInfo!');
            return $this->sendFailResponse(400,40000);
        }
        return $this->sendSuccessResponse($shop_info);
    }

    public function collectDianPingShop(Shop $shop, ShopStatistic $sta, ShopDianping $dianping)
    {
        ini_set('max_execution_time', '0');
        $http = new Client();
        $this->local = dirname(dirname(dirname(dirname(__DIR__)))) . '/public/upload/image/';
        $ossClient = new OssClient(env('ALIYUN_ID'), env('ALIYUN_KEY'), env('ALIYUN_ENDPOINT'));
        $bucket = env('ALIYUN_BUCKET');
        $rep_shop_ids = $dianping->pluck('shop_id')->toArray();
        $rep_shop_name = $shop->leftJoin('districts', 'shops.city_id', '=', 'districts.id')->where('shops.status','=',1)->pluck('districts.name','shops.title')->toArray();
        if(isset($_GET['city'])&&isset($_GET['category'])){
            $params['city'] = $_GET['city'];
            $params['category'] = $_GET['category'];
        }else{
            return $this->sendFailResponse(400, 10001);
        }
        if(isset($_GET['sort'])){
            $params['sort'] = $_GET['sort'];
        }else{
            $params['sort'] = '默认';
        }
        if(!empty($_GET['limit'])) {
            $params['limit'] = abs(intval($_GET['limit']));
        }else{
            $params['limit'] = 1500;
        }
        if(!empty($_GET['shop_photo_limit'])) {
            $params['shop_photo_limit'] = abs(intval($_GET['shop_photo_limit']));
        }else{
            $params['shop_photo_limit'] = 0;
        }
        if(!empty($_GET['proxy'])&&!empty($_GET['proxy_port'])){
            $proxy = $_GET['proxy'];
            $proxy_port = abs(intval($_GET['proxy_port']));
            $proxy_str = '&proxy='.$proxy.'&proxy_port='.$proxy_port;
            if(!empty($_GET['proxy_user'])&&!empty($_GET['proxy_pwd'])){
                $proxy_user = $_GET['proxy_user'];
                $proxy_pwd = $_GET['proxy_pwd'];
                $proxy_str = $proxy_str.'&proxy_user='.$proxy_user.'&proxy_pwd='.$proxy_pwd;
            }
        }else{
            $proxy_str = '';
        }
        if(isset($_GET['use_random_proxy'])&&in_array($_GET['use_random_proxy'],[0,1,2])) {
            $params['use_random_proxy'] = $_GET['use_random_proxy'];
        }else{
            $params['use_random_proxy'] = 0;
        }
        $get_dp_shop_ids = $http->get('https://api.beboy.me/api/getDianPingShopIds?city=' . $params['city'] . '&category=' . $params['category'] . '&sort=' . $params['sort'] . '&limit=' . $params['limit'] . '&rep_shop_ids=1');
        $get_dp_shop_ids = json_decode($get_dp_shop_ids->getBody(), true);
        if(empty($get_dp_shop_ids['data'][0])||!is_numeric($get_dp_shop_ids['data'][0])){
            Log::debug('Fail to getDainPingShopId');
            return $this->sendFailResponse(400, 40000);
        }
        $dp_shop_ids = json_encode($get_dp_shop_ids['data']);
        $get_dp_shop_info = $http->get('https://api.beboy.me/api/getDianPingShopInfo?shop_ids='.$dp_shop_ids.'&shop_photo_limit='.$params['shop_photo_limit'].'&use_random_proxy='.$params['use_random_proxy'].$proxy_str);
        $dp_shop_info = json_decode($get_dp_shop_info->getBody(), true);
        if (!empty($dp_shop_info['data'])&&$dp_shop_info['status_code']==200) {
            foreach ($dp_shop_info['data'] as $v) {
                if (!empty(array_intersect_assoc([$v['full_name']=>$v['city_name'].'市'],$rep_shop_name))) {
                    $shop = $shop->select('shops.*')->leftJoin('districts', 'shops.city_id', '=', 'districts.id')->where('shops.title', '=', $v['full_name'])->where('districts.name', '=', $v['city_name'].'市')->first();
                    if(in_array($shop->shop_id,$rep_shop_ids)){
                        $shop = new Shop();
                    }
                    Log::info('Repetitive shop name='.$v['full_name'].' city name='.$v['city_name'].'市');
                }
                switch ($v['main_category_name']) {
                    case 'KTV':
                        $shop->type = 2;
                        break;
                    case '量贩式KTV':
                        $shop->type = 2;
                        break;
                    case '会所型KTV':
                        $shop->type = 3;
                        break;
                    case '足疗按摩':
                        $shop->type = 5;
                        break;
                    case '洗浴/汗蒸':
                        $shop->type = 1;
                        break;
                    case '洗浴':
                        $shop->type = 1;
                        break;
                    case '清吧':
                        $shop->type = 4;
                        break;
                    case '夜店':
                        $shop->type = 4;
                        break;
                    case 'Live House':
                        $shop->type = 4;
                        break;
                    case '闹吧':
                        $shop->type = 4;
                        break;
                    case '其他酒吧':
                        $shop->type = 4;
                        break;
                    default:
                        Log::info('Shop type incorrect,shop name='.$v['full_name'].',type name='.$v['main_category_name']);
                        continue 2;
                }
                $shop->title = $v['full_name'];
                $shop->consumption = $v['avg_price'];
                if (!empty($v['cover'])) {
                    try {
                        $img = file_get_contents($v['cover']);
                        $ext = pathinfo($v['cover'], PATHINFO_EXTENSION);
                        if(!empty($ext)){
                            $cover = uniqid().'.'.$ext;
                        }else{
                            $cover = uniqid();
                        }
                        file_put_contents($this->local . $cover, $img);
                        if(!empty($shop->cover)){
                            $ossClient->deleteObject($bucket, $shop->cover);
                        }
                        $shop->cover = 'image/' . $cover;
                        $object = $shop->cover;
                        $ossClient->uploadFile($bucket, $object, $this->local . $cover);
                    } catch (\Exception $e) {
                        Log::debug('------>Fail in cover dp_shop_id=' . $v['shop_id']);
                        continue;
                    }
                }
                $shop->phone = $v['phone'];
                $shop->address = $v['street_address'];
                $shop->longitude = $v['shop_glng'];
                $shop->latitude = $v['shop_glat'];
                if (!empty($v['photos'])) {
                    if(!empty($shop->images)){
                        $images = json_decode($shop->images,true);
                    }else{
                        $images = [];
                    }
                    foreach ($v['photos'] as $photo) {
                        if (!empty($photo)) {
                            try {
                                $img = file_get_contents($photo);
                                $ext = pathinfo($photo, PATHINFO_EXTENSION);
                                if(!empty($ext)){
                                    $image = uniqid().'.'.$ext;
                                    $images[] = 'image/'.$image.'?x-oss-process=style/dp';
                                }else{
                                    $image = uniqid();
                                    $images[] = 'image/'.$image;
                                }
                                file_put_contents($this->local . $image, $img);
                                $object = 'image/'.$image;
                                $ossClient->uploadFile($bucket, $object, $this->local . $image);
                            } catch (\Exception $e) {
                                Log::debug('------>Fail in images dp_shop_id=' . $v['shop_id']);
                                continue 2;
                            }
                        }
                    }
                    if (!empty($images)) {
                        $shop->images = json_encode($images);
                    }
                }
                $shop->save();
                $sta->firstOrCreate(['shop_id'=>$shop->shop_id]);
                $dianping->shop_id = $shop->shop_id;
                $dianping->dp_shop_id = $v['shop_id'];
                $dianping->save();
                Log::debug('------>success shop_id='.$shop->shop_id.'  dp_shop_id='.$dianping->dp_shop_id);
                $sta = new ShopStatistic();
                $dianping = new ShopDianping();
                $shop = new Shop();
            }
        }else{
            Log::debug('Fail to getDianPingShopInfo');
            return $this->sendFailResponse(400, 40000);
        }
        Log::debug('Complete to collectDianPingShop!');
        return $this->sendSuccessResponse([]);
    }

    public function locationToAddress(Client $client, Shop $shop, District $district){
        if(isset($_GET['start_shop_id'])&&isset($_GET['end_shop_id'])){
            $start_shop_id = $_GET['start_shop_id'];
            $end_shop_id = $_GET['end_shop_id'];
            if(!is_numeric($start_shop_id)||!is_numeric($end_shop_id)){
                return $this->sendFailResponse('400','10002','参数错误');
            }
        }else{
            return $this->sendFailResponse('400','10001','参数缺失');
        }
        $map_api = 'http://apis.map.qq.com/ws/geocoder/v1/';
        if(isset($_GET['key'])){
            $key = $_GET['key'];
        }else{
            $key = 'I3OBZ-MBSRQ-WBJ5P-G5VZS-QGAIF-Y7B27';//我的key:'AGOBZ-3PAWS-7QQO3-6LPPW-UGE3E-M5BKA'
        }
        $shops = $shop->where('shop_id', '>=', $start_shop_id)->where('shop_id', '<=', $end_shop_id)->get();
        foreach ($shops as $k => $v) {
            if(empty($v['latitude'])||empty($v['longitude'])){
                Log::debug('no latitude or longitude shop_id='.$v['shop_id']);
                continue;
            }
            $location = $v['latitude'].','.$v['longitude'];
            $rs = $client->get($map_api.'?location='.$location.'&key='.$key);
            $data = json_decode($rs->getBody(), true);
            if(empty($data['result']['address_component']['city'])){
                Log::debug('Fail no city shop_id='.$v['shop_id']);
                $microsecond = rand(200000,250000);
                usleep($microsecond);
                continue;
            }
            $city_data = $district->where('type',2)->where('name', $data['result']['address_component']['city'])->first();
            if(empty($city_data)){
                Log::debug('Fail in city shop_id='.$v['shop_id']);
                $microsecond = rand(200000,250000);
                usleep($microsecond);
                continue;
            }
            $district_data = $district->where('name',$data['result']['address_component']['district'])->where('parent_id',$city_data['id'])->first();
            if(empty($district_data)){
                if($data['result']['address_component']['city']=='东莞市'){
                    $district_data = $district->find(441999);
                }elseif($data['result']['address_component']['city']=='中山市'){
                    $district_data = $district->find(442099);
                }else{
                    Log::debug('Fail in district shop_id='.$v['shop_id']);
                    $microsecond = rand(200000,250000);
                    usleep($microsecond);
                    continue;
                }
            }
            $province_data = $district->getById($city_data['parent_id']);
            if(empty($province_data)){
                Log::debug('Fail in province shop_id='.$v['shop_id']);
                $microsecond = rand(200000,250000);
                usleep($microsecond);
                continue;
            }
            $v->province_id = $province_data['id'];
            $v->city_id = $city_data['id'];
            $v->district_id = $district_data['id'];
            $v->save();
            Log::debug('Success shop_id='.$v['shop_id']);
            $microsecond = rand(200000,250000);
            usleep($microsecond);
        }
        return $this->sendSuccessResponse([]);
    }

    public function baiduToTencentLocations(Client $client, Shop $shop)
    {
        if (isset($_GET['start_shop_id']) && isset($_GET['end_shop_id'])) {
            $start_shop_id = $_GET['start_shop_id'];
            $end_shop_id = $_GET['end_shop_id'];
            if (!is_numeric($start_shop_id) || !is_numeric($end_shop_id)) {
                return $this->sendFailResponse('400', '10002', '参数错误');
            }
        } else {
            return $this->sendFailResponse('400', '10001', '参数缺失');
        }
        if (isset($_GET['key'])) {
            $key = $_GET['key'];
        } else {
            $key = 'I3OBZ-MBSRQ-WBJ5P-G5VZS-QGAIF-Y7B27';//我的key:'AGOBZ-3PAWS-7QQO3-6LPPW-UGE3E-M5BKA'
        }
        $api = 'http://apis.map.qq.com/ws/coord/v1/translate';
        $type = 3;//百度经纬度
        if (isset($_GET['limit'])) {
            $limit = abs(intval($_GET['limit']));
        } else {
            $limit = 40;
        }
        $shop->where('shop_id', '>=', $start_shop_id)->where('shop_id', '<=', $end_shop_id)
            ->chunk($limit, function ($shops) use ($client, $api, $type, $key) {
            $locations = '';
            foreach ($shops as $shop) {
                $locations = $locations . $shop['latitude'] . ',' . $shop['longitude'] . ';';
            }
            $locations = rtrim($locations, ";");
            $rs = $client->get($api . '?locations=' . $locations . '&type=' . $type . '&key=' . $key);
            $data = json_decode($rs->getBody(), true);
            if (isset($data['status']) && $data['status'] == 0) {
                foreach ($shops as $k => $v) {
                    $v->longitude = $data['locations'][$k]['lng'];
                    $v->latitude = $data['locations'][$k]['lat'];
                    $v->save();
                    Log::debug('Success shop_id=' . $v['shop_id']);
                }
            } else {
                Log::debug('Fail to translate locations,response='.$rs->getBody());
                return false;
            }
            $microsecond = rand(200000, 250000);
            usleep($microsecond);
        });
        return $this->sendSuccessResponse([]);
    }

    public function collectXdailiFreeProxy(){

    }

    public function coordinateToAddress(Client $client, Shop $shop, District $district){
        $map_url = 'http://api.map.baidu.com/geocoder/v2/';
        $params = [
            'ak' => 'tCECvhbGo6XXWFHoswsE4f2UIKkiD9fY',
            'callback' => 'renderReverse',
            'output' => 'json',
            'pois' => 0
        ];
        $shops = $shop->where('shop_id', '>=', 9267)->where('shop_id', '<=', 9688)->get();
        foreach ($shops as $k => $v) {
            if(empty($v['latitude'])||empty($v['longitude'])){
                Log::debug('no latitude or longitude shop_id='.$v['shop_id']);
                continue;
            }
            $params['location'] = $v['latitude'].','.$v['longitude'];
            $rs = $client->post($map_url, ['form_params' => $params]);
            $data = json_decode($rs->getBody(), true);
            if(empty($data['result']['addressComponent']['district'])){
                Log::debug('no coordinate shop_id='.$v['shop_id']);
                continue;
            }
            $city_data = $district->where('type',2)->where('name', $data['result']['addressComponent']['city'])->first();
            if(empty($city_data)){
                Log::debug('Fail in city shop_id='.$v['shop_id']);
                continue;
            }
            $district_data = $district->where('name',$data['result']['addressComponent']['district'])->where('parent_id',$city_data['id'])->first();
            if(empty($district_data)){
                Log::debug('Fail in district shop_id='.$v['shop_id']);
                continue;
            }
            $province_data = $district->getById($city_data['parent_id']);
            if(empty($province_data)){
                Log::debug('Fail in province shop_id='.$v['shop_id']);
                continue;
            }
            $v->province_id = $province_data['id'];
            $v->city_id = $city_data['id'];
            $v->district_id = $district_data['id'];
            $v->save();
            Log::debug('Success shop_id='.$v['shop_id']);
        }
        return $this->sendSuccessResponse([]);
    }

    public function coordinateToAddressDetail(Client $client, Shop $shop, $id){
        $map_url = 'http://api.map.baidu.com/geocoder/v2/';
        $params = [
            'ak' => 'tCECvhbGo6XXWFHoswsE4f2UIKkiD9fY',
            'callback' => 'renderReverse',
            'output' => 'json',
            'pois' => 0
        ];
        $shop_data = $shop->where('shop_id', $id)->first();
        $params['location'] = $shop_data['latitude'].','.$shop_data['longitude'];
        $rs = $client->post($map_url, ['form_params' => $params]);
        $data = json_decode($rs->getBody(), true);
        return $this->sendSuccessResponse($data);
    }

    public function check_url($url, $id){
//        return true;
        try{
            $data = get_headers($url,1);
            if(preg_match('/200/',$data[0])){
                return true;
            }else{
                return false;
            }
        }catch (\Exception $e){
            Log::debug('------>Fail in id='.$id);
            return false;
        }
    }

    public function createUser(User $user){
//        Log::debug(1111111);
        $all_user = $user->where('is_bot', 0)->where('user_id', '<=', 10)->get();
        $client = new JMessage(env('JMSG_APPKEY'), env('JMSG_SECRET'));
        $j_user = new \JMessage\IM\User($client);
        $admin = new Admin($client);
        $friend = new Friend($client);
        $i = 1;
        foreach($all_user as $cur_user){
//            $j_user->register("beboy_".$cur_user->user_id, md5($cur_user->user_id), $cur_user->nickname, URL::getImage($cur_user->cover));
            $rs = $admin->register([
                'username' => "beboy_".$cur_user->user_id,
                'password' => md5($cur_user->user_id),
                'nickname' => $cur_user->nickname,
                'avatar' => URL::getImage($cur_user->cover),
            ]);
//            $rs = $friend->add("beboy_".$cur_user->user_id, [
//                'beboy_3',
//                'beboy_4',
//                'beboy_5',
//                'beboy_6',
//                'beboy_7',
//            ]);
//            $rs = $j_user->show("beboy_".$cur_user->user_id);
            Log::debug(json_encode($rs));
//            if($i % 10 == 0){
//                sleep(1);
//            }
//            $i++;
        }
        return $this->sendSuccessResponse([]);
    }

    public function addFriends($from, $to){
        $data = Easemob::singleton()->addFriend($from, $to);
        return $this->sendSuccessResponse($data);
    }

    public function sendMsg(MsgSystem $msgSystem){
//        $msgSystem->to_id = 220;
//        $msgSystem->message = Msg::welcome_msg();
//        $msgSystem->save();
        $data = Easemob::singleton()->sendText(6, 'users', ['220','3763'], 'Hello, earth', ['user_id'=>6]);
//        $data = Easemob::singleton()->sendCmd(6, 'chatgroups', ['1497950471066'], 'Hello, earth', ['user_id'=>6]);
//        dispatch(new SendReceiveHongBaoMsgJob(1));
        return $this->sendSuccessResponse($data);
    }

    public function createdBot(User $user){
        $http = new Client();
        $this->local = dirname(dirname(dirname(dirname(__DIR__)))).'/public/upload/image/';
        $ossClient = new OssClient(env('ALIYUN_ID'), env('ALIYUN_KEY'), env('ALIYUN_ENDPOINT'));
        $bucket = env('ALIYUN_BUCKET');
        for($i=19684711; $i<19700000; $i++){
            try{
                $data = $http->get('http://www.huajiao.com/user/'.$i);
                $html = $data->getBody();
            }catch (\Exception $e){
                Log::debug('------>Fail in url id='.$i);
                continue;
            }
            preg_match('/<div class="avatar"><img.+src=\"(.+?)\" alt=""><\/div>/u', $html, $match);
            if(empty($match[1])){
                Log::debug('------>Fail in avatar id='.$i);
                continue;
            }
            $avatar = $match[1];
            preg_match('/\/(\w*-*\w*\.(jpg|gif|bmp|bnp|png|jpeg))/u', $avatar, $match);
            if(empty($match[1])){
                Log::debug('------>Fail in image id='.$i);
                continue;
            }
            $image = $match[1];

            preg_match('/<h3>\s*(.+?)\s*<span class="level/u', $html, $match);
            if(empty($match[1]) || mb_strlen($match[1], 'UTF-8') > 100){
                Log::debug('------>Fail in nickname id='.$i);
                continue;
            }
            $nickname = $match[1];

            $user_data = $user->firstOrNew(['nickname'=>$nickname]);
            $user_data->cover = 'image/'.$image;
            try{
                $img = file_get_contents($avatar);
                file_put_contents($this->local.$image, $img);
                $object = $user_data->cover;
                $ossClient->uploadFile($bucket, $object, $this->local.$image);
            }catch (\Exception $e){
                Log::debug('------>Fail in oss id='.$i);
                continue;
            }
            $user_data->is_bot = 1;
            $user_data->save();
            Log::debug('------>Success in id='.$i);
            sleep(10);
        }
        return $this->sendSuccessResponse([]);
    }

    public function changePost(User $user, Post $post)
    {
        $post_data = $post->all();
        foreach($post_data as $v){
            $bot = $user->where('is_bot', 1)->inRandomOrder()->first();
            $v->user_id = $bot->user_id;
            $v->save();
        }
        return $this->sendSuccessResponse([]);
    }

    public function districtFirstLetter(District $district){
        $data = $district->all();
        foreach($data as $v){
            $v->first_letter = $this->getFirstCharter($v->name);
            $v->save();
        }
        return $this->sendSuccessResponse([]);
    }

    private function getFirstCharter($str){

        if(empty($str)){return '';}

        $fchar=ord($str{0});

        if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str{0});

        $s1=iconv('UTF-8','gb2312//TRANSLIT//IGNORE',$str);

        $s2=iconv('gb2312','UTF-8//TRANSLIT//IGNORE',$s1);

        $s=$s2==$str?$s1:$str;

        $asc=ord($s{0})*256+ord($s{1})-65536;

        if($asc>=-20319&&$asc<=-20284) return 'A';

        if($asc>=-20283&&$asc<=-19776) return 'B';

        if($asc>=-19775&&$asc<=-19219) return 'C';

        if($asc>=-19218&&$asc<=-18711) return 'D';

        if($asc>=-18710&&$asc<=-18527) return 'E';

        if($asc>=-18526&&$asc<=-18240) return 'F';

        if($asc>=-18239&&$asc<=-17923) return 'G';

        if($asc>=-17922&&$asc<=-17418) return 'H';

        if($asc>=-17417&&$asc<=-16475) return 'J';

        if($asc>=-16474&&$asc<=-16213) return 'K';

        if($asc>=-16212&&$asc<=-15641) return 'L';

        if($asc>=-15640&&$asc<=-15166) return 'M';

        if($asc>=-15165&&$asc<=-14923) return 'N';

        if($asc>=-14922&&$asc<=-14915) return 'O';

        if($asc>=-14914&&$asc<=-14631) return 'P';

        if($asc>=-14630&&$asc<=-14150) return 'Q';

        if($asc>=-14149&&$asc<=-14091) return 'R';

        if($asc>=-14090&&$asc<=-13319) return 'S';

        if($asc>=-13318&&$asc<=-12839) return 'T';

        if($asc>=-12838&&$asc<=-12557) return 'W';

        if($asc>=-12556&&$asc<=-11848) return 'X';

        if($asc>=-11847&&$asc<=-11056) return 'Y';

        if($asc>=-11055&&$asc<=-10247) return 'Z';

        return null;

    }

    public function jobTest(){
        dispatch(new TestJob());
    }

    public function testCache(){
        $value = Cache::remember('key1', Carbon::now()->addMinutes(10), function () {
            return 'val';
        });
        return $value;
    }

    public function testValidator(Request $request){
        $validator = Validator::make($request->all(), [
            'test' => 'required|in:1',
        ], [
            'test.required' => '10001',
            'test.in' => '10002',
        ]);
        var_dump(\GuzzleHttp\json_encode($request->all()));
        if ($validator->fails()) {
            $key = array_keys($validator->errors()->messages());
            return $this->sendFailResponse(400, $validator->errors()->first(), $key[0]);
        }
    }

    public function changeEasemobNickname(User $users){
//        $data = Easemob::singleton()->editNickname(6,'系统消息');
//        Easemob::singleton()->sendText(
//            99,
//            'users',
//            [220],
//            'test',
//            ['user_id'=>99, 'type'=>3, 'auth'=>1]
//        );
//        $data = Easemob::singleton()->createUser(98, md5(98), 'test_99');
        $user = $users->whereRaw('nickname is not null')->where('is_bot',0)->get();
        foreach($user as $v){
            Easemob::singleton()->editNickname($v->user_id,$v->nickname);
        }
        return $this->sendSuccessResponse([]);
    }

    public function getGroup(User $user, CoverDecorator $coverDecorator, Group $group){
        $rs = [];
        $groups = Easemob::singleton()->getGroupsForUser(103324);
        if(isset($groups['error'])){
            return $this->sendFailResponse(400, 40400);
        }
        $user->addDecorator($coverDecorator);
        $group->addDecorator($coverDecorator);
        foreach($groups['data'] as $k => $v){
            $rs['list'][$k]['groupid'] = $v['groupid'];
            $rs['list'][$k]['groupname'] = $v['groupname'];
            $group_data = $group->getGroup($v['groupid']);
            $rs['list'][$k]['cover'] = empty($group_data['cover'])?'':$group_data['cover'];
            $members = Easemob::singleton()->getGroupUsers($v['groupid']);
            if(isset($members['error']) || !is_array($members['data'])){
                return $this->sendFailResponse(400, 40400);
            }
            $data = [];
            foreach($members['data'] as $member){
                $data['members'][] = isset($member['member'])?$member['member']:$member['owner'];
                if(isset($member['owner'])){
                    $data['owner_id'] = $member['owner'];
                }
            }
            $rs['list'][$k]['members'] = $user->getUserListByUserId($data['members']);
            $rs['list'][$k]['owner_id'] = $data['owner_id'];
        }
        return $this->sendSuccessResponse($rs);
    }

    public function getMobileCityId(){
        $data = DB::select("select * from users where mobile is not null and mobile_city_id is null and user_id>=40143");
        foreach($data as $v){
            dispatch(new GetMobileCityIdJob($v->user_id));
        }
    }

    public function testWhatEverINeed(){
//        $http = new Client();
//        for($i=0; $i<100; $i++){
//            $data = $http->get('http://app.yuce168.com/Apis/HuangLi.aspx?date=20171219&key=0e759935564dcc63');
//            echo $data->getStatusCode()."\n\r";
//        }
        return $this->sendSuccessResponse([]);
    }

    public function collectHZLMShop(HZLM $hzlm)
    {
        ini_set('max_execution_time', '0');
        if(isset($_GET['start_hz_id'])&&isset($_GET['end_hz_id'])){
            $start_hz_id = $_GET['start_hz_id'];
            $end_hz_id = $_GET['end_hz_id'];
            if(!is_numeric($start_hz_id)||!is_numeric($end_hz_id)){
                return $this->sendFailResponse('400','10002','参数错误');
            }
        }else{
            return $this->sendFailResponse('400','10001','参数缺失');
        }
        $rep_hz_id = $hzlm->pluck('hz_id')->toArray();
        if(!empty($_GET['proxy'])&&!empty($_GET['proxy_port'])){
            $proxy = $_GET['proxy'];
            $proxy_port = abs(intval($_GET['proxy_port']));
            if(!empty($_GET['proxy_user'])&&!empty($_GET['proxy_pwd'])){
                $proxy_user = $_GET['proxy_user'];
                $proxy_pwd = $_GET['proxy_pwd'];
            }
        }
        if(isset($_GET['use_aby_proxy'])&&$_GET['use_aby_proxy']==1) {
            $use_aby_proxy = $_GET['use_aby_proxy'];
        }else{
            $use_aby_proxy = 0;
        }
        $success_one = false;
        for ($hz_id=$start_hz_id;$hz_id<=$end_hz_id;$hz_id++){
            if(in_array($hz_id,$rep_hz_id)){
                continue;
            }
            $shop_api = 'https://www.royalleauge.info/api';
            for($i=3;$i>0;$i--){
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $shop_api);
                $json = [
                    'm'=>'e4dce46f7634e88be7616694caa79b25',
                    'n'=>'ShopDetails',
                    'q'=>[
                      'id'=>$hz_id
                    ],
                    's'=>'6ylgst69lw2tvywd10gcoa4uyqudgv0y'
                ];
                $post_data=[
                    'json'=>json_encode($json)
                ];
                if($use_aby_proxy==1){//阿布云HTTP代理隧道动态版
                    $proxy = 'http-dyn.abuyun.com';
                    $proxy_port = 9020;
                    $proxy_user = 'H3W545ZSP4VM250D';
                    $proxy_pwd = 'B9EC39E61333D50B';
                }
                if(!empty($proxy)&&!empty($proxy_port)){
                    curl_setopt($ch, CURLOPT_PROXY, $proxy); //代理服务器地址
                    curl_setopt($ch, CURLOPT_PROXYPORT, $proxy_port); //代理服务器端口
                    curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); //使用http代理模式
                    if(!empty($proxy_user)&&!empty($proxy_pwd)){
                        curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC); //代理认证模式
                        curl_setopt($ch, CURLOPT_PROXYUSERPWD, "$proxy_user:$proxy_pwd"); //http代理认证帐号，username:password的格式
                    }
                }
                curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Accept-Encoding:gzip',
                    'User-Agent:okhttp/3.4.1',
                    'Content-Length:'.(170+strlen($hz_id)),
                    'Content-Type:application/x-www-form-urlencoded',
                    'Connection:Keep-Alive',
                    'Host:www.royalleauge.info'
                ));
                curl_setopt($ch, CURLOPT_POST,true);
                curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($post_data));
                curl_setopt($ch, CURLOPT_ENCODING, "");
                curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);
                curl_setopt($ch, CURLOPT_MAXREDIRS,2);
                curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
                curl_setopt($ch, CURLOPT_TIMEOUT, 8);
                $file_contents = curl_exec($ch);
                curl_close($ch);
                preg_match('/{\"[\s\S]*\"}}/', $file_contents, $match);
                if(isset($match[0])) {
                    $shop_detail = json_decode(htmlspecialchars_decode($match[0]), true);
                    if (isset($shop_detail['q']['shop']['id'])) {
                        $hzlm->hz_id = (int)$shop_detail['q']['shop']['id'];
                        $hzlm->name = $shop_detail['q']['shop']['name'];
                        $hzlm->address = $shop_detail['q']['shop']['address'];
                        $hzlm->phone = $shop_detail['q']['shop']['mobile'];
                        $hzlm->longitude = (float)$shop_detail['q']['shop']['lng'];
                        $hzlm->latitude = (float)$shop_detail['q']['shop']['lat'];
                        $hzlm->save();
                        $hzlm = new HZLM();
                        $success_one = true;
                        Log::debug('Success to getHZLMShop,hz_id=' . $hz_id);
                        break;
                    } elseif ($i == 1) {
                        Log::debug('Fail to getHZLMShop,hz_id=' . $hz_id);
                        break;
                    }
                }elseif ($i == 1){
                    Log::debug('Fail to getHZLMShop,hz_id=' . $hz_id);
                    break;
                }
            }
        }
        if($success_one){
            Log::debug('Complete to collectHZLMShop!');
            return $this->sendSuccessResponse([]);
        }else{
            Log::debug('Fail to getHZLMShop!');
            return $this->sendFailResponse(400, 40000);
        }
    }

    public function locationToAddressForHZLM(Client $client, HZLM $hzlm, District $district){
        if(isset($_GET['start_id'])&&isset($_GET['end_id'])){
            $start_id = $_GET['start_id'];
            $end_id = $_GET['end_id'];
            if(!is_numeric($start_id)||!is_numeric($end_id)){
                return $this->sendFailResponse('400','10002','参数错误');
            }
        }else{
            return $this->sendFailResponse('400','10001','参数缺失');
        }
        $map_api = 'http://apis.map.qq.com/ws/geocoder/v1/';
        if(isset($_GET['key'])){
            $key = $_GET['key'];
        }else{
            $key = 'I3OBZ-MBSRQ-WBJ5P-G5VZS-QGAIF-Y7B27';//我的key:'AGOBZ-3PAWS-7QQO3-6LPPW-UGE3E-M5BKA'
        }
        $hzlm_shops = $hzlm->where('id', '>=', $start_id)->where('id', '<=', $end_id)->get();
        foreach ($hzlm_shops as $k => $v) {
            if(empty($v['latitude'])||empty($v['longitude'])){
                Log::debug('no latitude or longitude id='.$v['id']);
                continue;
            }
            $location = $v['latitude'].','.$v['longitude'];
            $rs = $client->get($map_api.'?location='.$location.'&key='.$key);
            $data = json_decode($rs->getBody(), true);
            if(empty($data['result']['address_component']['city'])){
                Log::debug('Fail no city id='.$v['id']);
                $microsecond = rand(200000,250000);
                usleep($microsecond);
                continue;
            }
            $city_data = $district->where('type',2)->where('name', $data['result']['address_component']['city'])->first();
            if(empty($city_data)){
                Log::debug('Fail in city id='.$v['id']);
                $microsecond = rand(200000,250000);
                usleep($microsecond);
                continue;
            }
            $district_data = $district->where('name',$data['result']['address_component']['district'])->where('parent_id',$city_data['id'])->first();
            if(empty($district_data)){
                if($data['result']['address_component']['city']=='东莞市'){
                    $district_data = $district->find(441999);
                }elseif($data['result']['address_component']['city']=='中山市'){
                    $district_data = $district->find(442099);
                }else{
                    Log::debug('Fail in district id='.$v['id']);
                    $microsecond = rand(200000,250000);
                    usleep($microsecond);
                    continue;
                }
            }
            $province_data = $district->getById($city_data['parent_id']);
            if(empty($province_data)){
                Log::debug('Fail in province id='.$v['id']);
                $microsecond = rand(200000,250000);
                usleep($microsecond);
                continue;
            }
            $v->province_id = $province_data['id'];
            $v->city_id = $city_data['id'];
            $v->district_id = $district_data['id'];
            $v->save();
            Log::debug('Success id='.$v['id']);
            $microsecond = rand(200000,250000);
            usleep($microsecond);
        }
        return $this->sendSuccessResponse([]);
    }

    public function createInviteCode(InviteCode $inviteCode){
        $min = 10000000;
        $max = 99999999;
        $count = 0;
        $return = [];
        while ($count < 100000) {
            $return[] = mt_rand($min, $max);
            $return = array_flip(array_flip($return));
            $count = count($return);
        }
        foreach($return as $v){
            $inviteCode->create(['code'=>$v]);
        }
    }
}